const STATUS_PENDING = 'pending';// 等待
const STATUS_FULFILLED = 'fulfilled';// 成功
const STATUS_REJECTED = 'rejected';// 失败

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (error) {
      this.reject(error)
    }
  }

  status = STATUS_PENDING;// promise状态

  value = undefined;// 成功值
  reason = undefined;// 失败原因

  successCallback = [];// 成功回调,存储多个函数
  failCallback = [];// 失败回调,存储多个函数

  resolve = value => { // 定义为箭头函数为this指向MyPromise本身
    if (this.status !== STATUS_PENDING) return;// 状态一旦确定不可更改
    this.status = STATUS_FULFILLED;// 改变状态
    this.value = value;// 保存成功值

    // 处理异步情况
    // this.successCallback && this.successCallback(this.value);// 如果存在成功回调调用该回调
    while (this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => { // 定义为箭头函数为this指向MyPromise本身

    if (this.status !== STATUS_PENDING) return;// 状态一旦确定不可更改
    this.status = STATUS_REJECTED;// 改变状态
    this.reason = reason;// 保存失败原因

    // 处理异步情况
    // this.failCallback && this.failCallback(this.reason);// 如果存在失败回调调用该回调
    while (this.failCallback.length) this.failCallback.shift()()
  }

  then(successCallback, failCallback) {// 判断状态执行相应回调函数
    successCallback = successCallback ? successCallback : value => value;// 如果不是回调函数直接向下传递
    failCallback = failCallback ? failCallback : reason => { throw reason };// 如果不是回调函数直接向下传递

    let newPromise = new MyPromise((resolve, reject) => {// 立即执行
      if (this.status === STATUS_FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);// 成功返回成功值
            resolvePromise(newPromise, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0);// 转换成异步才能获取到newPromise
      } else if (this.status === STATUS_REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);// 失败返回失败原因
            resolvePromise(newPromise, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0);// 转换成异步才能获取到newPromise
      } else { // 等待中，将成功回调和失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);// 成功返回成功值
              resolvePromise(newPromise, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0);// 转换成异步才能获取到newPromise
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);// 失败返回失败原因
              resolvePromise(newPromise, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0);// 转换成异步才能获取到newPromise
        });

      }
    })
    return newPromise;
  }

  finally(callback) {
    return this.then(
      value => {
        return MyPromise.resolve(callback()).then(() => value);
      },
      reason => {
        return MyPromise.resolve(callback()).then(() => { throw reason });
      }
    )
  }

  catch(failCallback) {
    return this.then(undefined, failCallback);
  }

  static all(array) {
    let result = [];// 存储结果
    let count = 0;// 计数器
    return new Promise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value;
        count++;
        if (count === array.length) {
          resolve(result)
        }
      }
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element instanceof MyPromise) {
          // promise对象
          element.then(value => addData(index, value), reason => reject(reason))
        } else {
          // 普通值
          addData(index, element);
        }
      }
    })
  }

  static resolve(value) {
    if (value instanceof MyPromise) return value;
    return new Promise((resolve, reject) => {
      resolve(value)
    })
  }
}

function resolvePromise(promise, x, resolve, reject) {
  if (promise === x) return reject(new TypeError('Chaining cycle detected for promise #<Promise>'));// 自返回抛出错误
  // 判断x的值是普通值还是promise对象
  if (x instanceof MyPromise) {// promise对象
    x.then(resolve, reject);// 把resolve和reject传递给下一个promise对象
  } else {// 普通值
    resolve(x);// 成功返回值传递给下一个promise对象
  }
}

module.exports = MyPromise
